const Log = require('../model/log.model');
const User = require('../model/user.model');

const sequelize = require('sequelize');

// 服务层 读写数据库
class LogService {
    // 添加日志信息
    async createLog(ctx, log_detail) {
        // console.log(ctx.state);
        let user = ctx.state.user;
        let user_id = user.id;
        let ip = ctx.ip || ctx.req.connection.remoteAddress || ctx.socket.remoteAddress;
        let user_ip = ip.replace('::ffff:', '')
        // console.log(ctx.ip.replace('::ffff:', ''));
        // console.log(ctx.req.connection.remoteAddress.replace('::ffff:', ''));
        // console.log(ctx.socket.remoteAddress.replace('::ffff:', ''));
        let res = await Log.create({user_id, log_detail, user_ip});
        return res;
    }

    async getLogInfo({id, user_id, log_detail, user_ip, pageInfo}) {
        let whereObj = {};
        id && Object.assign(whereObj, {id});
        user_id && Object.assign(whereObj, {user_id});
        log_detail && Object.assign(whereObj, {log_detail});
        user_ip && Object.assign(whereObj, {user_ip});


        let count = await Log.count({where: whereObj});
        let res;
        if(count !== 0){
            let _pageInfo = {};
            if (pageInfo) {
                let {pageIndex, pageSize} = JSON.parse(pageInfo);
                _pageInfo = {
                    limit: pageSize,
                    offset: (pageIndex - 1) * pageSize
                }
            }
            res = await Log.findAll({
                order: [
                    ['createdAt', 'DESC'],
                ],
                // attributes: [],
                where: whereObj,
                // 关联查询
                include: [{
                    model: User,
                    attributes: {exclude: ['password']},
                    as: 'userInfo', // 不用as，默认就是user的表名
                    // required: false
                }],
                ..._pageInfo
            });
        }
        return {list: res, count: count} || '';
    }
}

module.exports = new LogService();